package com.example.demo.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.common.Result;
import com.example.demo.entity.ScShift;
import com.example.demo.entity.SysUser;
import com.example.demo.mapper.ScShiftMapper;
import com.example.demo.service.impl.ScRecordServiceImpl;
import com.example.demo.service.impl.ScShiftServiceImpl;
import com.example.demo.utils.TokenUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/shift")
public class ScShiftController {

    @Autowired
    ScShiftServiceImpl scShiftService;
    @Autowired
    ScRecordServiceImpl scRecordService;
    @Resource
    ScShiftMapper scShiftMapper;
    private static String[] str = {"√", "□", "∆"};
    private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private static SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM");

    @PostMapping("/save")
    public Result<?> save(@RequestBody ScShift scShift, HttpServletRequest request) throws Exception {
        SysUser user = TokenUtils.getUserInfo(request);
        if (user == null)
            return Result.error("500", "未获取到user信息");

        scShift.setIsDeleted(false);
        int i = 0;
        Field[] fields = scShift.getClass().getDeclaredFields();
        for (Field field : fields) {
            //设置允许通过反射访问私有变量
            field.setAccessible(true);
            //获取字段的值
            if (field.get(scShift) != null) {
                if (Arrays.asList(str).contains(field.get(scShift).toString())) {
                    i++;
                }
            }
        }
        scShift.setShouldDay(i);
        if (scShift.getId() != null) {
            scShift.setModifyUser(user.getPeopleName());
            scShift.setModifyTime(dateFormat.format(new Date()));
        } else {
            scShift.setCreateUser(user.getPeopleName());
            scShift.setCreateTime(dateFormat.format(new Date()));
        }
        return Result.success(scShiftService.save(scShift));
    }

    @PostMapping("/update")
    public Result<?> update(@RequestBody Map<String, String> map, HttpServletRequest request) throws Exception {
        SysUser user = TokenUtils.getUserInfo(request);
        if (user == null)
            return Result.error("500", "未获取到user信息");

        ScShift scShift = scShiftMapper.selectById(map.get("id"));
        if (scShift == null) return Result.error("404", "找不到该排班表记录");
        scShift.setName(map.get("name"));
        scShift.setDepartment(map.get("department"));
        scShift.setMonth(map.get("month"));
        scShift.setDay01(map.get("day01"));
        scShift.setDay02(map.get("day02"));
        scShift.setDay03(map.get("day03"));
        scShift.setDay04(map.get("day04"));
        scShift.setDay05(map.get("day05"));
        scShift.setDay06(map.get("day06"));
        scShift.setDay07(map.get("day07"));
        scShift.setDay08(map.get("day08"));
        scShift.setDay09(map.get("day09"));
        scShift.setDay10(map.get("day10"));
        scShift.setDay11(map.get("day11"));
        scShift.setDay12(map.get("day12"));
        scShift.setDay13(map.get("day13"));
        scShift.setDay14(map.get("day14"));
        scShift.setDay15(map.get("day15"));
        scShift.setDay16(map.get("day16"));
        scShift.setDay17(map.get("day17"));
        scShift.setDay18(map.get("day18"));
        scShift.setDay19(map.get("day19"));
        scShift.setDay20(map.get("day20"));
        scShift.setDay21(map.get("day21"));
        scShift.setDay22(map.get("day22"));
        scShift.setDay23(map.get("day23"));
        scShift.setDay24(map.get("day24"));
        scShift.setDay25(map.get("day25"));
        scShift.setDay26(map.get("day26"));
        scShift.setDay27(map.get("day27"));
        scShift.setDay28(map.get("day28"));
        scShift.setDay29(map.get("day29"));
        scShift.setDay30(map.get("day30"));
        scShift.setDay31(map.get("day31"));

        scShift.setIsDeleted(false);
        int i = 0;
        Field[] fields = scShift.getClass().getDeclaredFields();
        for (Field field : fields) {
            //设置允许通过反射访问私有变量
            field.setAccessible(true);
            //获取字段的值
            if (field.get(scShift) != null) {
                if (Arrays.asList(str).contains(field.get(scShift).toString())) {
                    i++;
                }
            }
        }
        scShift.setShouldDay(i);
        if (scShift.getId() != null) {
            scShift.setModifyUser(user.getPeopleName());
            scShift.setModifyTime(dateFormat.format(new Date()));
        } else {
            scShift.setCreateUser(user.getPeopleName());
            scShift.setCreateTime(dateFormat.format(new Date()));
        }
        return Result.success(scShiftService.updateById(scShift));
    }

    @GetMapping("/{id}")
    public Result<?> getById(@PathVariable long id) throws Exception {
        ScShift scShift = scShiftMapper.selectById(id);
        if (scShift == null) return Result.error("404", "找不到该id对应的排班表");
        return Result.success(scShiftMapper.selectById(scShift));
    }

    @DeleteMapping("/{id}")
    public Result<?> delete(@PathVariable long id) throws Exception {
        ScShift scShift = scShiftMapper.selectById(id);
        if (scShift == null) return Result.error("404", "找不到该id对应的排班表");
        scShift.setIsDeleted(true);
        return Result.success(scShiftMapper.updateById(scShift));
    }

    @GetMapping("/name")
    public Result<?> getName(@RequestParam(defaultValue = "") String date) {
        String date1;
        if (StrUtil.isEmpty(date))
            return Result.error("401","缺乏月份信息");
        try {
            Date dateTime = dateFormat1.parse(date);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(dateTime);
            calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) - 1);
            date1 = dateFormat1.format(calendar.getTime());
        } catch (ParseException e) {
            return Result.error("401", "日期格式错误");
        }

        LambdaQueryWrapper<ScShift> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(ScShift::getIsDeleted, false);
        wrapper.eq(ScShift::getMonth, date1);
        wrapper.isNotNull(ScShift::getName);
        wrapper.ne(ScShift::getName, "");
        List<ScShift> list = scShiftMapper.selectList(wrapper);
        List<ScShift> list1 = new ArrayList<>();
        for (ScShift item : list) {
            item.setId(null);
            item.setMonth(date);
            list1.add(item);
        }

        if (scShiftService.saveBatch(list1))
            return Result.success();
        else
            return Result.error("401", "一点问题");
    }

    @GetMapping("/list")
    public synchronized Result<?> findPage(@RequestParam(defaultValue = "1") Integer pageNum,
                                           @RequestParam(defaultValue = "10") Integer pageSize,
                                           @RequestParam(defaultValue = "") String date,
                                           @RequestParam(defaultValue = "") String name,
                                           @RequestParam(defaultValue = "") String department) {
        LambdaQueryWrapper<ScShift> wrapper = Wrappers.lambdaQuery();
        if (StrUtil.isNotBlank(department)) {
            wrapper.like(ScShift::getDepartment, department);
        }
        if (StrUtil.isNotBlank(date)) {
            wrapper.eq(ScShift::getMonth, date);
        }
        if (StrUtil.isNotBlank(name)) {
            wrapper.eq(ScShift::getName, name);
        }
        wrapper.eq(ScShift::getIsDeleted, false);
        Page<ScShift> scShiftPage = scShiftMapper.selectPage(new Page<>(pageNum, pageSize), wrapper);
        return Result.success(scShiftPage);
    }

    @GetMapping("/export/{department}/{date}")
    public void export(@PathVariable String department, @PathVariable String date, HttpServletResponse response){
        Map<String, Object> excelMap = new HashMap<>();
        LambdaQueryWrapper<ScShift> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(ScShift::getDepartment, department).eq(ScShift::getMonth, date);
        List<ScShift> list = scShiftMapper.selectList(wrapper);
        int i = 1;
        for (ScShift scShift : list) {
            scShift.setId(i);
            i++;
        }
        excelMap.put("list", list);
        excelMap.put("department", department);
        excelMap.put("date", date);

        Workbook workBook = null;
        try {
            TemplateExportParams params = new TemplateExportParams("static/sc/shift_template.xlsx", true);
            workBook = ExcelExportUtil.exportExcel(params, excelMap);
            response.setHeader("content-Type", "application/octet-stream");
            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode("月度物业人员排班表.xlsx", "UTF-8"));
            workBook.write(response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("导出异常");
        }finally {
            if (workBook != null) {
                try {
                    workBook.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
